package com.kitty.game.activity.service.task;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.ActivityService;
import com.kitty.game.artifact.ArtifactService;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossNpcParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TaskSet;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.npc.service.NewNpcService;
import com.kitty.game.role.model.Role;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import org.nutz.lang.util.NutMap;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@Component
public class XiuFaTaskHandler
        extends TaskActivityHandler {
    private final TaskType TASK_TYPE = TaskType.XIU_FA;
    private static final int SAODANG_JIFEN_COST = 20;
    private static final int MIN_TEAM_COUNT = 1;
    private static final int MAX_TEAM_COUNT = 1;
    private final int ACCEPT_MIN_LEVEL = 70;
    private static final int REWARD_TASK_ID = 2504;
    private final int TASK_ID_AT_NPC = 2500; // taskSet中2500为第一个修法任务
    private final String TEAM_COUNT_NOT_ENOUGH = "法宝的修法任务考验修行者的实力，至少组队#R{0}#n人，至多组队#R{1}#n人。[离开]";
    private final String LEVEL_NOT_ENOUGH = "#Y{0}#n角色低于#R{1}级#n，无法接受修法任务。[离开]";
    private final String ACCEPTED = "你已经领取#R修法#n任务，还不快去接受指点。[离开]";
    private final String NOT_ACCEPTED = "你还未领取#R修法#n任务。[离开]";
    private final String NOT_WEAR_ARTIFACT = "你未穿戴法宝，请穿戴法宝后重试。[离开]";
    private final String REMAIN_COUNT_NOT_ENOUGH = "#Y{0}#n今日#R修法#n次数已达上限，请明日再来。[离开]";
    private static final String MESSAGE_TEMPLATE = "你的队伍成功领取#R修法#n任务, 请速去挑战#Y{0}#n。";
    private static final String FINISH_FIGHT = "你已完成修法挑战，请找#R多宝道人#n领取奖励。";
    private static final String NO_REWARD_TIP = "今日修法获得战斗奖励已达#R{0}#n次，无法获得奖励！";
    private final int NPC_BOSS_COUNT = 5;
    private static final String NOT_FETCH_REWARD = "请先完成所有修法神兽挑战！[离开]";

    // 扫荡修法任务
    public void saoDangTask(Role role, NPC npc) {
        int remainCount = SpringUtils.getActivityService().getRemainCount(role, ActivityType.XIUFA_TASK);
        if (remainCount <= 0) {
            sendNpcContent(role, npc, MessageFormat.format(REMAIN_COUNT_NOT_ENOUGH, role.getName()));
            return;
        }
        //取消修法消耗积分
//        if (role.getActivity().getRechargeScore() < SAODANG_JIFEN_COST) {
//            MessagePusher.pushMessage(role, new RespNotifyMiscEx("积分不足，无法扫荡！"));
//            return;
//        } else {
        //SpringUtils.getRoleService().substractChargeScore(role, SAODANG_JIFEN_COST);

        // 保险起见，将所有修法过程中的任务框全部删除
        for (int taskId = TASK_ID_AT_NPC; taskId <= REWARD_TASK_ID; taskId++) {
            TaskSet rewardTaskSet = this.taskService.getTaskSet(taskId, role);
            super.deleteTaskForSingle(role, rewardTaskSet);
        }

        for (int i = 1; i <= remainCount; i++) {
            (SpringUtils.getBean(ActivityService.class)).addFinishCount(role, ActivityType.XIUFA_TASK, 1);
        }

        sendRewards(role);
       // }

    }

    @Override
    public TaskSet getAcceptingTask(Role role, NPC npc) {
        return this.taskService.getTaskSet(TASK_ID_AT_NPC, role);
    }

    // 判断角色role是否已经领取过修法任务
    private boolean isAcceptedTask(Role role) {
        return this.getTaskSetByType(role) != null;
    }

    @Override
    public String canAcceptTask(Role role, TaskSet taskSet, boolean auto) {
        RoleEquip roleEquip = SpringUtils.getBean(EquipService.class).getRoleEquipByPos(role, 9);
        if (roleEquip == null) {
            return NOT_WEAR_ARTIFACT;
        }
        // 挑战人数限制
        int teamCount = this.teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT || teamCount > MAX_TEAM_COUNT) {
            return MessageFormat.format(TEAM_COUNT_NOT_ENOUGH, MIN_TEAM_COUNT, MAX_TEAM_COUNT);
        }

        Team team = this.teamService.getTeam(role.getRoleId());
        // 判断是否已经做完了修法任务
        Object isTip = role.getTalk().popChooseParam("xiufa_no_reward_tip");
        if (isTip == null) {
            ActivityService activityService = SpringUtils.getBean(ActivityService.class);
            StringBuilder remainCountNotEnoughNames = new StringBuilder();
            for (Member member : team.getList()) {
                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                int remainCount = activityService.getRemainCount(memberRole, ActivityType.XIUFA_TASK);
                if (member == null || !member.isInTeam() || memberRole == null || remainCount > 0) continue;
                if (remainCountNotEnoughNames.length() > 0) {
                    remainCountNotEnoughNames.append("、");
                }
                remainCountNotEnoughNames.append(member.getName());
            }
            if (remainCountNotEnoughNames.length() > 0) {
                return MessageFormat.format(REMAIN_COUNT_NOT_ENOUGH, remainCountNotEnoughNames);
            }
        }

        StringBuilder levelNotEnoughNames = new StringBuilder();
        ArrayList<Member> members = team.getList();
        for (Member member : members) {
            if (member == null || !member.isInTeam() || member.getLevel() >= ACCEPT_MIN_LEVEL) continue;
            if (levelNotEnoughNames.length() > 0) {
                levelNotEnoughNames.append("、");
            }
            levelNotEnoughNames.append(member.getName());
        }
        if (levelNotEnoughNames.length() > 0) {
            return MessageFormat.format(LEVEL_NOT_ENOUGH, levelNotEnoughNames, ACCEPT_MIN_LEVEL);
        }
        boolean isMemberNotAccept = false;
        for (Member member : team.getList()) {
            Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
            if (member == null || !member.isInTeam() || memberRole == null || this.isAcceptedTask(memberRole)) continue;
            isMemberNotAccept = true;
            break;
        }
        if (!isMemberNotAccept) {
            return ACCEPTED;
        }
        return null;
    }

    public void doAfterAccept(Role role, TaskSet taskSet) {
        super.doAfterAccept(role, taskSet);
        this.autoWalk(role, taskSet);
    }

    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setTaskName(taskSet.getTaskName());
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        if (activityService.getFinishCount(role, ActivityType.XIUFA_TASK) >= ActivityType.XIUFA_TASK.getTotalCount()) {
            taskInfo.setShow_name("修法任务已完成");
        }
        taskInfo.setQuit((short) taskSet.getGiveUp());
        taskInfo.setTaskInfo(taskSet.getTaskJieshao());
        taskInfo.setTaskZhiyin(taskSet.getTaskZhiyin());
        taskInfo.setTaskJiangli(taskSet.getTaskGift());
        return taskInfo;
    }

    @Override
    public String getPrompt(NPC npc) {
        if (npc.getName().equals("多宝道人")) {
            return FINISH_FIGHT;
        }
        return MessageFormat.format(MESSAGE_TEMPLATE, npc.getName());
    }

    @Override
    public BossNpcParam newBossNpcParam(Role var1, TaskSet var2) {
        return null;
    }

    @Override
    public String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    public TaskType getTaskType() {
        return TASK_TYPE;
    }

    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {
        RoleEquip roleEquip = SpringUtils.getBean(EquipService.class).getRoleEquipByPos(role, 9);
        if (roleEquip == null) {
            return NOT_WEAR_ARTIFACT;
        }
        int teamCount = this.teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT || teamCount > MAX_TEAM_COUNT) {
            return MessageFormat.format(TEAM_COUNT_NOT_ENOUGH, MIN_TEAM_COUNT, MAX_TEAM_COUNT);
        }
        TaskSet taskSet = this.getTaskSetByBossNpc(role, bossNpc);
        if (taskSet == null) {
            return NOT_ACCEPTED;
        }
        StringBuilder levelNotEnoughNames = new StringBuilder();
        Team team = teamService.getTeam(role.getRoleId());
        ArrayList<Member> members = team.getList();
        for (Member member : members) {
            if (member == null || !member.isInTeam() || member.getLevel() >= ACCEPT_MIN_LEVEL) continue;
            if (levelNotEnoughNames.length() > 0) {
                levelNotEnoughNames.append("、");
            }
            levelNotEnoughNames.append(member.getName());
        }
        if (levelNotEnoughNames.length() > 0) {
            return MessageFormat.format(LEVEL_NOT_ENOUGH, levelNotEnoughNames, ACCEPT_MIN_LEVEL);
        }
        return null;
    }

    @Override
    public void doStartFight(Role role, TaskSet taskSet, NPC bossNpc) {
        List<BossParam> bossParamList = this.newBossParamList(role, bossNpc);
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, this.getFightType(role), taskSet.getId(), bossNpc.getId());
        bossService.startFightToBoss(role, bossFightParam);
        String fightStartPromp = this.getFightStartPrompt(bossNpc);
        if (fightStartPromp != null) {
            this.teamService.pushMessage(role, new RespMsg(fightStartPromp));
        }
    }

    // 新增重写
    private List<BossParam> newBossParamList(Role role, NPC npc) {
        ArrayList<BossParam> bossParamList = new ArrayList<>();
        int count = NPC_BOSS_COUNT;
        NewBossService bossService = SpringUtils.getBean(NewBossService.class);
        BossSet bossSet = bossService.getBossSet(npc.getName());
        bossParamList.add(new BossParam(bossSet, npc.getName()));
        for (int i = 1; i < count; ++i) {
            bossSet = bossService.getBossSet(npc.getName() + "分身");
            bossParamList.add(new BossParam(bossSet, bossSet.getName()));
        }
        return bossParamList;
    }

    public String getFightStartPrompt(NPC bossNpc) {
        return null;
    }

    @Override
    protected int getFightType(Role var1) {
        return Const.fightType_xiufa;
    }

    @Override
    protected void addActivityFinishCount(Role role, TaskSet taskSet) {
        (SpringUtils.getBean(ActivityService.class)).addFinishCount(role, ActivityType.XIUFA_TASK, 1);
    }

    @Override
    protected void giveReward(Role role, NutMap reward, TaskSet taskSet, int currPetId) {

        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        int finishCount = activityService.getFinishCount(role, ActivityType.XIUFA_TASK);
        if (finishCount > ActivityType.XIUFA_TASK.getTotalCount()) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(MessageFormat.format(NO_REWARD_TIP, ActivityType.XIUFA_TASK.getTotalCount())));
            return;
        }

    }


    public void fetchXiuFaReward(Role role, NPC npc) {
        String check = this.checkFetchReward(role);
        if (check != null) {
            (SpringUtils.getBean(NewNpcService.class)).sendNpcContent(role, npc, check);
            return;
        }
        // 删除任务面板框，增加修法次数
        TaskSet rewardTaskSet = this.taskService.getTaskSet(REWARD_TASK_ID, role);
        super.deleteTaskForSingle(role, rewardTaskSet);
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.XIUFA_TASK, 1);

        // 发送奖励
        sendRewards(role);
    }

    public void sendRewards(Role role) {
        // 开双倍，给道法
        NutMap nutMap = role.getPropsStatus();
        int point = nutMap.getInt("role");
        ArtifactService artifactService = SpringUtils.getBean(ArtifactService.class);
        if (nutMap.getInt("roleStatus") == 1 && point >= 4) {
            nutMap.setv("role", (point - 4));
            role.save();
            artifactService.addArtifactExp(true, role);
        } else {
            artifactService.addArtifactExp(false, role);
        }
    }

    private String checkFetchReward(Role role) {
        if (!this.isCanFetchReward(role)) {
            return NOT_FETCH_REWARD;
        }
        int remainCount = SpringUtils.getActivityService().getRemainCount(role, ActivityType.XIUFA_TASK);
        if (remainCount <= 0) {
            MessagePusher.pushMessage(role, new RespMsg(MessageFormat.format(REMAIN_COUNT_NOT_ENOUGH, role.getName())));
            return "";
        }
        return null;
    }

    private boolean isCanFetchReward(Role role) {
        TaskSet rewardTaskSet = this.taskService.getTaskSet(REWARD_TASK_ID, role);
        return this.taskService.isTaskAccepted(role, rewardTaskSet);
    }

    // 暂时置空
    @Override
    protected void doBeforeDelete(Role role, TaskSet taskSet) {

    }

    @Override
    protected void doAfterDelete(Role role, TaskSet taskSet) {
        String content = this.acceptTaskAuto(role, taskSet);
        Team team = this.teamService.getTeam(role.getRoleId());
        if (team != null && team.isLeader(role.getRoleId()) && content == null) {
            TaskSet newTaskSet = this.getTaskSetByType(role);
            this.autoWalk(role, newTaskSet);
        }
    }

    // 接收下一个任务
    private String acceptTaskAuto(Role role, TaskSet taskSet) {
        TaskSet nextTaskSet = this.taskService.getNextTask(taskSet, role);
        return this.acceptTask(role, nextTaskSet, true);
    }

    // 自动导航到下一个任务
    private void autoWalk(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = this.getTaskInfo(role, taskSet);
        if (taskInfo == null) {
            return;
        }
        RespAutoWalk respAutoWalk = new RespAutoWalk();
        respAutoWalk.setTaskName(taskInfo.getTaskName());
        respAutoWalk.setDest(taskInfo.getTaskZhiyin());
        MessagePusher.pushMessage(role, respAutoWalk);
    }

    @Override
    public boolean isCreateNpcForFight(TaskSet var1) {
        return false;
    }

    public void doFightFail(Role role, TaskSet taskSet, FightEndEvent fightEndEvent) {
        super.doFightFail(role, taskSet, fightEndEvent);
        this.teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }
}
